package com.vichat.task;

import com.jcraft.jsch.ChannelSftp;
import com.mchange.io.FileUtils;
import com.vichat.common.constant.GlobalConstant;
import com.vichat.common.ffmpeg.util.FFMpegUtil;
import com.vichat.common.util.*;
import com.vichat.common.vo.ftp.Ftp;
import com.vichat.res.entity.FtpConfig;
import com.vichat.res.service.ICfgService;
import com.vichat.res.vo.RecFileVO;
import com.vichat.task.entity.CfgTaskParam;
import com.vichat.task.service.ITask;
import com.vichat.task.service.ITaskService;
import com.vichat.user.entity.SysStaticData;
import com.vichat.user.service.IStaticDataService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.file.Files;
import java.util.*;

/**
 * Created by wangluyin on 2017/9/6.
 * 数据备份
 */
@Component("MediaRecFileTransferTask")
public class MediaRecFileTransferTask implements ITask {
    private static transient final Logger logger = LoggerFactory.getLogger(MediaRecFileTransferTask.class);

    @Autowired
    ITaskService taskService;
    @Autowired
    IStaticDataService staticDataService;

    @Override
    public String doTask(long cfgTaskId) throws Exception {
        List<CfgTaskParam> cfgTaskParams = taskService.getCfgTaskParamById(cfgTaskId);
        if (cfgTaskParams != null) {
            String localPath = "";
            String suffix = "";
            String backUpPath = "";

            for (CfgTaskParam cfgTaskParam : cfgTaskParams) {
                if (cfgTaskParam.getParamName().equals("localPath")) {
                    localPath = cfgTaskParam.getRemark();
                }
                if (cfgTaskParam.getParamName().equals("suffix")) {
                    suffix = cfgTaskParam.getRemark();
                }
                if (cfgTaskParam.getParamName().equals("backUpPath")) {
                    backUpPath = cfgTaskParam.getRemark();
                }
            }

            if (!StringUtils.isNotBlank(localPath) || !StringUtils.isNotBlank(backUpPath)) {
                logger.error("请检查配置");
            } else {
                MediaRecFileTransferThread thread = new MediaRecFileTransferThread(localPath, suffix, backUpPath);
                thread.start();
            }
        }
        return "success";
    }

    class MediaRecFileTransferThread extends Thread {
        private String suffix;
        private String localPath;
        private String backUpPath;

        MediaRecFileTransferThread(String localPath, String suffix, String backUpPath) {
            this.localPath = localPath;
            this.suffix = suffix;
            this.backUpPath = backUpPath;
        }

        public void run() {
            try {
                while (true) {
                    double cup = SystemMsgUtil.cpuUsage();

                    logger.info("CPU:" + cup + "%");

                    if (cup > 80) {
                        Thread.sleep(10 * 1000);//如果CPU占用率超过80%，则不继续解析文件
                    }

                    mkdirs(localPath);
                    File fileFolder = new File(localPath);
                    File[] files = fileFolder.listFiles();

                    for (File file : files) {
                        String fileName = file.getName();
                        long fileSize = file.length();

                        //transfer
                        if (StringUtils.endsWithIgnoreCase(fileName, ".dat") && fileSize > 0) {//是普通文件，且文件不是空文件
                            logger.debug("filename:" + fileName);
                            FFMpegUtil.datToMp4(localPath, FileTypeUtil.getFileNameNoEx(fileName));
                        }
                    }

                    fileFolder = new File(localPath);
                    File[] mp4Files = fileFolder.listFiles();

                    for (File file : mp4Files) {

                        String fileName = file.getName();
                        String fileNameNoEx = FileTypeUtil.getFileNameNoEx(fileName);
                        long fileSize = file.length();

                        if (fileName.contains("video") && StringUtils.endsWithIgnoreCase(fileName, ".mp4") && fileSize > 0 && suffix.equals("wav")) {//是普通文件，且文件不是空文件
                            logger.debug("filename:" + fileName);
                            FFMpegUtil.mp4Towav(localPath, fileNameNoEx);

                            deleteFile(file);
                            continue;
                        }
                        if (fileName.contains("audio") && StringUtils.endsWithIgnoreCase(fileName, ".mp4") && fileSize > 0) {
                            logger.debug("filename:" + fileName);
                            FFMpegUtil.mp4Tomp3(localPath, fileNameNoEx);

                            deleteFile(file);
                            continue;
                        }
                        if (StringUtils.endsWithIgnoreCase(fileName, ".dat") && fileSize > 0) {
                            mkdirs(backUpPath + "/" + DateUtil.getToday("yyyyMMdd"));
                            File backupFile = new File(backUpPath + "/" + DateUtil.getToday("yyyyMMdd") + "/" + fileName);
                            if (!backupFile.exists()) {
                                file.renameTo(backupFile);
                            }else{
                                if(backupFile.length() == fileSize) {
                                    file.deleteOnExit();
                                }
                            }
                            continue;
                        }
                    }

                    Thread.sleep(20 * 1000);
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getMessage(), e);
            }
        }

        public void deleteFile(File file) {
            if (file.exists()) {
                file.delete();
            }
        }

        public void mkdirs(String dirPath) {
            try {
                File dir = new File(dirPath);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("创建文件夹目录出错", e);
            }


        }


    }
}
